package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.entity.User;
import com.echo.exception.ArticleException;
import com.echo.service.ArticleService;
import com.echo.servlet.BaseServlet;
import com.echo.util.SessionUtils;
import com.echo.util.MarkdownUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 编辑文章Servlet：处理/article-edit请求
 */
@WebServlet({"/article-edit", "/echo-network/article-edit"})
public class EditArticleServlet extends BaseServlet {
    private final ArticleService articleService = new ArticleService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 校验登录状态（未登录重定向到登录页）
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect("/echo-network/login.html");
            return;
        }

        // 2. 获取文章ID
        String articleIdStr = request.getParameter("id");
        if (articleIdStr == null || articleIdStr.isEmpty()) {
            request.setAttribute("errorMsg", "文章ID不能为空");
            forward(request, response, "/error/404.html");
            return;
        }

        try {
            Integer articleId = Integer.parseInt(articleIdStr);
            // 3. 查询文章详情
            Article article = articleService.findById(articleId);
            if (article == null) {
                request.setAttribute("errorMsg", "文章不存在");
                forward(request, response, "/error/404.html");
                return;
            }

            // 4. 校验权限（确保是作者本人才能编辑）
            if (!article.getAuthorUsername().equals(loginUser.getUsername())) {
                request.setAttribute("errorMsg", "无权编辑此文章");
                forward(request, response, "/error/404.html");
                return;
            }

            // 5. 设置文章信息，使用BaseServlet的forward方法转发到编辑页面
            // 这样可以确保Thymeleaf正确渲染article对象到页面
            request.setAttribute("article", article);
            forward(request, response, "/article-edit.html");

        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "无效的文章ID");
            forward(request, response, "/error/404.html");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误，请稍后再试");
            forward(request, response, "/error/500.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 校验登录状态（未登录重定向到登录页）
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect("/echo-network/login.html");
            return;
        }

        // 2. 设置请求编码（防止中文乱码）
        request.setCharacterEncoding("UTF-8");

        // 3. 接收表单参数
        String articleIdStr = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");

        if (articleIdStr == null || articleIdStr.isEmpty()) {
            request.setAttribute("errorMsg", "文章ID不能为空");
            forward(request, response, "/error/404.html");
            return;
        }

        Integer articleId;
        try {
            articleId = Integer.parseInt(articleIdStr);
            
            // 4. 校验权限（确保是作者本人才能编辑）
            Article existingArticle = articleService.findById(articleId);
            if (existingArticle == null) {
                request.setAttribute("errorMsg", "文章不存在");
                forward(request, response, "/error/404.html");
                return;
            }
            
            if (!existingArticle.getAuthorUsername().equals(loginUser.getUsername())) {
                request.setAttribute("errorMsg", "无权编辑此文章");
                forward(request, response, "/error/404.html");
                return;
            }

            // 5. 封装更新的文章对象
            Article article = new Article();
            article.setId(articleId);
            article.setTitle(title);
            article.setContent(content);
            // 使用MarkdownUtils将Markdown内容转换为HTML
            String htmlContent = MarkdownUtils.markdownToHtml(content);
            article.setHtmlContent(htmlContent);
            // 设置作者信息以通过参数校验
            article.setAuthorUsername(loginUser.getUsername());

            // 6. 调用Service更新文章
            System.out.println("准备更新文章，ID: " + articleId + ", 标题: " + title);
            articleService.update(article);
            System.out.println("文章更新成功，即将重定向到article-show");

            // 7. 更新成功：设置成功提示并重定向到我的文章页
            request.getSession().setAttribute("successMsg", "文章编辑成功！");
            // 使用request.getContextPath()获取上下文路径，确保重定向路径正确
            String redirectUrl = request.getContextPath() + "/article-show";
            System.out.println("重定向URL: " + redirectUrl);
            response.sendRedirect(redirectUrl);

        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "无效的文章ID");
            forward(request, response, "/error/404.html");
        } catch (ArticleException e) {
            // 8. 业务异常（参数非法等）：回显错误信息到编辑页
            request.setAttribute("errorMsg", e.getMessage());
            request.setAttribute("title", title);
            request.setAttribute("content", content);
            request.setAttribute("articleId", articleIdStr); // 传递文章ID，确保表单能正确提交
            // 在异常情况下，我们不使用existingArticle，而是直接转发错误信息
            forward(request, response, "/article-edit.html");
        } catch (SQLException e) {
            // 9. 数据库异常：显示系统错误
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误，文章更新失败");
            forward(request, response, "/error/500.html");
        }
    }
}